<script setup lang="ts">
  import EpTickets from '~icons/ep/tickets';
  import { type DistributionData, type DistributionRequest, getDistributionData, getDistributionDataById } from '@/api/ledger-management.ts';
  import { formatNumberWithMoney } from '@/utils/numb.ts';
  import OrderList from '@/views/app-main/ledger-management/drama-data-statistics/components/orderList.vue';

  const baseLoadPageRef: $RefComp<'BaseLoadPage'> = ref(null);
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });
  const dataLoad = ref<boolean>(false);
  const orderListRef: $RefComp<typeof OrderList> = ref(null);
  const pageData = ref<DistributionData | null>(null);
  const dramaOptions = ref<{ dramaId: number; dramaTitle: string }[]>([]);
  const dataRange = ref<[string, string] | undefined>();
  const filterData = ref<DistributionRequest>({
    startDate: '',
    endDate: '',
    investmentChannel: 'juliang',
    dramaIds: [],
    range: -1,
  });
  // 投光渠道
  const advertisingChannels = ref([
    {
      label: '巨量',
      value: 'juliang',
    },
    // {
    //   label: "磁力",
    //   value: "cili"
    // }, {
    //   label: "腾讯",
    //   value: "tengxun"
    // },
    {
      label: '星图',
      value: 'xingtu',
    },
  ]);
  const dramaSelestorDisabled = computed(() => {
    return [0, 1].includes(dramaOptions.value.length);
  });

  const getViewData = async (pageLoading = true) => {
    if (filterData.value.range === -1 && Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = dataRange.value[0];
      filterData.value.endDate = dataRange.value[1];
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      if (dramaOptions.value.length) {
        if (!filterData.value.dramaIds || !filterData.value.dramaIds.length) {
          pageData.value = null;
          return;
        }
      }

      pageLoading && (pageLoad.loadState = true);
      !pageLoading && (dataLoad.value = true);

      if (dramaOptions.value.length === 0) {
        const { data: dramaList } = await getDistributionDataById();
        if (dramaList && dramaList.length > 0) {
          dramaOptions.value = dramaList;
          filterData.value.dramaIds = dramaList.map((drama) => drama.dramaId);
        }
      }

      const { data } = await getDistributionData(filterData.value);
      pageData.value = data;
      pageLoad.loadState = false;
      dataLoad.value = false;
      // eslint-disable-next-line no-use-before-define, @typescript-eslint/no-use-before-define
      getFilter();
    } catch (error) {
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
      dataLoad.value = false;
    }
  };

  const showOrderList = (flag: number) => {
    orderListRef.value?.show({
      startDate: filterData.value.startDate,
      endDate: filterData.value.endDate,
      dramaIds: filterData.value.dramaIds,
      condition: flag,
      range: filterData.value.range,
      investmentChannel: filterData.value.investmentChannel,
    });
  };

  export interface StatisticsItem {
    name: string;
    flag: keyof DistributionData | 'dividendAmount';
    unit?: string;
    color?: string;
    icon?: boolean;
    condition?: number;
    format: (val: DistributionData | null) => string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '总充值金额',
      flag: 'totalRecharge',
      unit: '￥',
      color: 'var(--el-color-primary-dark-2)',
      format(val: any) {
        return `${formatNumberWithMoney(val?.totalRecharge) || '0'}`;
      },
    },
    {
      name: '总首充金额',
      flag: 'firstRecharge',
      unit: '￥',
      color: 'var(--el-color-success-dark-2)',
      format(val: any) {
        return `${formatNumberWithMoney(val?.firstRecharge) || '0'}`;
      },
    },
    {
      name: '总复充金额',
      flag: 'repeatRecharge',
      unit: '￥',
      format(val: any) {
        return `${formatNumberWithMoney(val?.repeatRecharge) || '0'}`;
      },
    },
    {
      name: '总注册用户数',
      flag: 'totalUsers',
      format(val: any) {
        return `${val?.totalUsers || '0'}`;
      },
    },
    {
      name: '已付款总订单数',
      flag: 'paidNums',
      icon: true,
      condition: 1,
      format(val: any) {
        return `${val?.paidNums || '0'}`;
      },
    },
    {
      name: '未付款订单数',
      flag: 'unpaidNums',
      icon: true,
      condition: 2,
      format(val: any) {
        return `${val?.unpaidNums || '0'}`;
      },
    },
    {
      name: '注册用户arpu值 = 总充值金额/总注册用户数',
      flag: 'userArpu',
      format(val: any) {
        return `${val?.userArpu || '0'}`;
      },
    },
    {
      name: '充值用户arpu值 = 总充值金额/充值用户数',
      flag: 'rechargeArpu',
      format(val: any) {
        return `${val?.rechargeArpu || '0'}`;
      },
    },
    {
      name: '首充总单数 = 首充人数',
      flag: 'firstNums',
      icon: true,
      condition: 3,
      format(val: any) {
        return `${val?.firstNums || '0'}`;
      },
    },
    {
      name: '复充总单数',
      flag: 'repeatNums',
      icon: true,
      condition: 4,
      format(val: any) {
        return `${val?.repeatNums || '0'}`;
      },
    },
    {
      name: '复充总人数 = 首次复充人数 = 首次复充订单数',
      flag: 'repeatMens',
      format(val: any) {
        return `${val?.repeatMens || '0'}`;
      },
    },
    {
      name: '首次复充金额',
      flag: 'firstRepeatAmount',
      format(val: any) {
        return `${val?.firstRepeatAmount || '0'}`;
      },
    },
  ]);

  const prizeList = ref<any[]>([]);

  const getFilter = () => {
    switch (filterData.value.investmentChannel) {
      case 'xingtu': {
        const addList: StatisticsItem[] = [
          {
            name: '分成金额',
            unit: '￥',
            flag: 'dividendAmount',
            format(val: any) {
              return `${formatNumberWithMoney(val?.dividendAmount) || '0'}`;
            },
          },
        ];
        prizeList.value = addList;
        break;
      }
      default:
        if (pageData?.value && pageData?.value.cost === null) {
          prizeList.value = [];
        } else {
          const addList: StatisticsItem[] = [
            {
              name: '消耗',
              unit: '￥',
              flag: 'cost',
              format(val: any) {
                return `${formatNumberWithMoney(val?.cost) || '0'}`;
              },
            },
            {
              name: '利润',
              unit: '￥',
              flag: 'profit',
              format(val: any) {
                return `${formatNumberWithMoney(val?.profit) || '0'}`;
              },
            },
          ];
          prizeList.value = addList;
        }

        break;
    }
  };
  onBeforeMount(() => {
    getViewData();
  });
</script>

<template>
  <base-load-page
    ref="baseLoadPageRef"
    :loadState="pageLoad.loadState"
    :description="pageLoad.description"
    :pageLoadButton="[{ text: '重新加载', callBack: () => getViewData() }]"
  >
    <div class="wrap">
      <el-scrollbar>
        <div class="query-wrapper">
          <el-radio-group v-model="filterData.range" @change="getViewData(false)">
            <el-radio-button :value="-1">全部</el-radio-button>
            <el-radio-button :value="1">今日</el-radio-button>
            <el-radio-button :value="2">昨日</el-radio-button>
            <el-radio-button :value="3">本周</el-radio-button>
            <el-radio-button :value="4">本月</el-radio-button>
          </el-radio-group>
          <div class="input-box">
            <el-select
              v-model="filterData.dramaIds"
              multiple
              collapseTags
              collapseTagsTooltip
              placeholder="短剧"
              :disabled="dramaSelestorDisabled"
              :clearable="false"
              style="width: 230px"
              @change="getViewData(false)"
            >
              <el-option v-for="i in dramaOptions" :key="i.dramaId" :label="i.dramaTitle" :value="i.dramaId"></el-option>
            </el-select>
            <el-select v-model="filterData.investmentChannel" clearable placeholder="投广渠道" style="width: 230px" @change="getViewData(false)">
              <el-option v-for="(i, key) in advertisingChannels" :key="key" :label="i.label" :value="i.value"></el-option>
            </el-select>
            <div v-show="filterData.range === -1" style="flex-grow: 0; width: 350px">
              <base-date-picker
                v-model="dataRange"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                type="daterange"
                startPlaceholder="开始日期"
                endPlaceholder="结束日期"
                clearable
                @change="getViewData(false)"
              ></base-date-picker>
            </div>
          </div>
        </div>
        <div v-loading="dataLoad" class="statistic-wrap">
          <div v-for="(i, key) in statisticsData" :key="key">
            <div class="statistic-card">
              <div class="statistic-value" :style="{ color: i.color }">
                <span>{{ i.unit }}{{ i.format(pageData) }}</span>
                <el-icon v-if="i.icon" @click="showOrderList(i.condition!)">
                  <ep-tickets></ep-tickets>
                </el-icon>
              </div>
              <div class="statistic-footer">
                <span>{{ i.name }}</span>
              </div>
            </div>
          </div>
          <div v-for="(i, key) in prizeList" :key="key">
            <div class="statistic-card">
              <div class="statistic-value" :style="{ color: i.color }">
                <span>{{ i.unit }}{{ i.format(pageData) }}</span>
                <el-icon v-if="i.icon" @click="showOrderList(i.condition!)">
                  <ep-tickets></ep-tickets>
                </el-icon>
              </div>
              <div class="statistic-footer">
                <span>{{ i.name }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <order-list ref="orderListRef"></order-list>
  </base-load-page>
</template>

<style scoped lang="scss">
  .wrap {
    width: 100%;
    height: 100%;
    padding: 10px;

    .query-wrapper .input-box {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      gap: 14px;
      margin: 18px 0;
    }

    .statistic-wrap {
      display: grid;
      flex: 1;
      flex-wrap: wrap;
      grid-template-columns: repeat(auto-fill, minmax(370px, 1fr));
      gap: 20px;

      .statistic-card {
        padding: 16px 60px 16px 20px;
        background-color: var(--el-color-info-light-9);
        border-radius: 6px;

        .statistic-value {
          font-size: 28px;
          color: var(--el-text-color-primary);

          .el-icon {
            margin-left: 4px;
            font-size: 20px;
            cursor: pointer;
          }
        }

        .statistic-footer {
          margin-top: 8px;
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
</style>
